package com.qumap.server;

import com.qumap.item.content.ObjectOnMap;
import com.qumap.item.content.ObjectOnMapShort;
import com.qumap.common.item.Operations;
import com.qumap.item.request.filter.entry.FilterEntry;
import com.qumap.server.filter.TestFilterObjectComparator;

import java.util.LinkedList;
import java.util.List;
import java.util.NavigableSet;
import java.util.TreeSet;

/**
 * Created by IntelliJ IDEA.
 * User: Admin
 * Date: 26.06.11
 * Time: 18:20
 * To change this template use File | Settings | File Templates.
 */
public class FilterProcessorHelper {
    public static final double LONGTITUDE_TEST = 30.422;
    public static final double LATTITUDE_TEST = 50.425;
    public static final double DELTA_STEP = 0.15;

    public static final int START_INDEX = 50;
    public static final int FINISH_INDEX = 150;

    private TreeSet<ObjectOnMapShort> object_set = new TreeSet<ObjectOnMapShort>(new TestFilterObjectComparator());


    public FilterProcessorHelper() {
        init();
    }

    protected void init() {
        ObjectOnMapShort operate_object;
        for(int i=START_INDEX; i<FINISH_INDEX;++i) {
            operate_object = generateObject(i);
            object_set.add(operate_object);
        }
    }


    protected ObjectOnMapShort generateObject(int index) {
        ObjectOnMapShort new_object = new ObjectOnMapShort();
        double longtitude = LONGTITUDE_TEST+generateDelta();
        double lattitude = LATTITUDE_TEST+generateDelta();

        new_object.setId(index);
        new_object.setLattitude(lattitude);
        new_object.setLongtitude(longtitude);

        return new_object;
    }

    private double generateDelta() {
        return Math.random()*DELTA_STEP;
    }

    public List<ObjectOnMapShort> getFilteredObjects(List<FilterEntry> filters) {

        NavigableSet<ObjectOnMapShort> subset = extract(object_set, filters.get(0));
        subset = extract(subset, filters.get(1));

        List<ObjectOnMapShort> filtered_objects = new LinkedList<ObjectOnMapShort>();
        filtered_objects.addAll(subset);

        return filtered_objects;
    }

    private NavigableSet<ObjectOnMapShort> extract(NavigableSet<ObjectOnMapShort> base_set, FilterEntry entry) {
        Operations operation = Operations.values()[entry.getOperation()];
        ObjectOnMapShort tmp_object = new ObjectOnMap(entry.getValue().intValue(), new Double(0), new Double(0));
        switch(operation) {
            case Above:
                return base_set.tailSet(tmp_object, false);
            case AboveOrEquals:
                return base_set.tailSet(tmp_object, true);
            case Below:
                return base_set.headSet(tmp_object, false);
            case BelowOrEquals:
                return base_set.headSet(tmp_object, true);
            case Equals:
            default:
                return null;

        }
    }

}
